//
//  PlayViewController.m
//  FAKER
//
//  Created by Jianwei on 15/11/2.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "PlayViewController.h"
#import "AllHeader.h"
#import "FitHeader.h"
@interface PlayViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)BaseClassTableView *tableView;
@property(nonatomic, retain)NSMutableArray *sectionArray;
@property(nonatomic, retain)NSMutableDictionary *headerPictureDic;
@property(nonatomic, retain)NSMutableDictionary *detailMessageDic;
@property(nonatomic, retain)NSMutableArray *messageArray;
@property(nonatomic, retain)NSMutableArray *picArray;
@property(nonatomic, retain)LQYItemsDetailViewController *IDVC;

@property(nonatomic, retain)NSString *cityName;

@property(nonatomic, retain)YHLoadingView *loadingView;
@end

@implementation PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"玩乐";
    _cityName = @"大连";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:_cityName style:UIBarButtonItemStylePlain target:self action:@selector(selectCity)];
    [self getData];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_sectionArray removeAllObjects];
        [self getData];
    }];
    
    _loadingView = [[YHLoadingView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49)];
    if (NSUSERDEFAULTS_NIGHT) {
        _loadingView.backgroundColor = [UIColor blackColor];
    }
    else{
        _loadingView.backgroundColor = [UIColor whiteColor];
    }
    [self.view addSubview:_loadingView];
}

-(void)viewWillAppear:(BOOL)animated
{
    if (NSUSERDEFAULTS_NIGHT) {
        _tableView.separatorStyle = 1;
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    }
    else{
        _tableView.separatorStyle = 0;
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    [self.navigationItem.rightBarButtonItem setTitle:_cityName];
}

-(void)selectCity
{
    void(^block)(NSString *) = ^(NSString *str){
        [_tableView.mj_header beginRefreshing];
        _cityName = str;
    };
    LQYSelectCityViewController *SCVC = [[LQYSelectCityViewController alloc]init];
    SCVC.block = block;
    [self.navigationController pushViewController:SCVC animated:YES];
}
#pragma mark    創建視圖并初始化數組字典
-(void)loadView
{
    [super loadView];
    self.sectionArray = [NSMutableArray array];
    self.detailMessageDic = [NSMutableDictionary dictionary];
    self.headerPictureDic = [NSMutableDictionary dictionary];
    self.messageArray = [NSMutableArray array];
    self.picArray = [NSMutableArray array];
    
    _tableView = [[BaseClassTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
}
#pragma mark    組的個數
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionArray.count;
}
#pragma mark    每組各有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_sectionArray[section] valueForKey:@"items"] count] + 1;
}
#pragma mark    每組中各行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return 100 * FITHEIGHT;
    }
    if ([[_sectionArray[indexPath.section] valueForKey:@"style"] isEqualToString:@"all_pic"])
    {
        return 212.5 * FITHEIGHT;
    }
    else
    {
        return 320 * FITHEIGHT;
    }
}

#pragma mark    cell的樣式
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifie = @"cell";
    BaseClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifie];
    if (!cell)
    {
        cell = [[BaseClassTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifie];
    }
#pragma mark    題目的cell
    LQYFirstPageTitleTableViewCell *titleCell = [[LQYFirstPageTitleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifie];
#pragma mark    只有圖片的cell
    LQYFirstPageOnlyImageTableViewCell *onlyImageCell = [[LQYFirstPageOnlyImageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifie];
#pragma mark    圖片和文字的cell
    LQYFirstPageImageAndLabelTableViewCell *imageAndLabelCell = [[LQYFirstPageImageAndLabelTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifie];
    
#pragma mark    為cell中元素賦值
    
    //第0行是title 其他行是內容
    if (indexPath.row == 0)
    {
        [titleCell.backImageView sd_setImageWithURL:[NSURL URLWithString:[[_sectionArray[indexPath.section] valueForKey:@"banner"] valueForKey:@"url"]]];
        cell = titleCell;
    }
    else
    {
        if ([[_sectionArray[indexPath.section] valueForKey:@"style"] isEqualToString:@"all_pic"])
        {
            [onlyImageCell.backImageView sd_setImageWithURL:[NSURL URLWithString:[[[_sectionArray[indexPath.section] valueForKey:@"items"][indexPath.row - 1] valueForKey:@"pic"] objectForKey:@"url"]]placeholderImage:[UIImage imageNamed:@"PlaceHolder"]];
            cell = onlyImageCell;
        }
        else
        {
           [imageAndLabelCell.topImageView sd_setImageWithURL:[NSURL URLWithString:[[[_sectionArray[indexPath.section] valueForKey:@"items"][indexPath.row - 1] valueForKey:@"pic"] objectForKey:@"url"]]placeholderImage:[UIImage imageNamed:@"PlaceHolder"]];
            imageAndLabelCell.titleLabel.text = [[_sectionArray[indexPath.section] valueForKey:@"items"][indexPath.row - 1] valueForKey:@"title"];
            imageAndLabelCell.introduceLabel.text = [[_sectionArray[indexPath.section] valueForKey:@"items"][indexPath.row - 1] valueForKey:@"content"];
            
            cell = imageAndLabelCell;
        }
    }
    
    cell.selectionStyle = 0;
    
    
    return cell;
}
#pragma mark    cell的點擊方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果key里有值  那麼跳頁否則不跳
    if (indexPath.row == 0){
      if ([_sectionArray[indexPath.section] valueForKey:@"more_info"]){
            LQYShowAllSelectionsViewController *SASVC = [[LQYShowAllSelectionsViewController alloc]init];
            SASVC.hidesBottomBarWhenPushed = YES;
            SASVC.carryTitleString = [_sectionArray[indexPath.section]valueForKey:@"title"];
            SASVC.carryLinkString = [[_sectionArray[indexPath.section]valueForKey:@"more_info"]valueForKey:@"api_url"];
            SASVC.carryStyleString = [_sectionArray[indexPath.section]valueForKey:@"style"];
            SASVC.carryTypeString = [_sectionArray[indexPath.section]valueForKey:@"more_type"];
            SASVC.carryRankNumber = [_sectionArray[indexPath.section]valueForKey:@"rank"];
            [self.navigationController pushViewController:SASVC animated:YES];
        }
    }
    else{
        _IDVC = [[LQYItemsDetailViewController alloc]init];
        if ([[_sectionArray[indexPath.section] valueForKey:@"rank"] isEqualToString:@"70"] || ![_sectionArray[indexPath.section] valueForKey:@"more_info"]){
            _IDVC.carryAdUrl = [[[[_sectionArray[indexPath.section]valueForKey:@"items"]objectAtIndex:indexPath.row - 1]valueForKey:@"web"]valueForKey:@"url"];
        }
        else{
            _IDVC.count = [[[[_sectionArray[indexPath.section]valueForKey:@"items"]objectAtIndex:indexPath.row - 1]valueForKey:@"article"]allKeys].count;
            _IDVC.carryCellStyle = [[[_sectionArray[indexPath.section]valueForKey:@"items"]objectAtIndex:indexPath.row - 1]valueForKey:@"tpl_cell_style"];
            
            if ([[_sectionArray[indexPath.section]valueForKey:@"more_type"] isEqualToString:@"items"]){
                NSDictionary *modalDic = [[[_sectionArray[indexPath.section]valueForKey:@"items"]objectAtIndex:indexPath.row - 1]valueForKey:@"article"];
                LQYJudgeArticleModal *modal = [[LQYJudgeArticleModal alloc] init];
                [modal setValuesForKeysWithDictionary:modalDic];
                _IDVC.articleModal = modal;
                _IDVC.carryTitleString = [[[_sectionArray[indexPath.section]valueForKey:@"items"]objectAtIndex:indexPath.row - 1]valueForKey:@"title"];
                _IDVC.carryAutherString = [[[[_sectionArray[indexPath.section] valueForKey:@"items"]objectAtIndex:indexPath.row - 1]objectForKey:@"article"]valueForKey:@"auther_name"];
                //給標識賦值
                _IDVC.tag = 0;
            }
            else{
                _IDVC.carryWeekendUrl = [[[[_sectionArray[indexPath.section]valueForKey:@"items"]objectAtIndex:indexPath.row - 1]valueForKey:@"weekend"]valueForKey:@"content_url"];
                _IDVC.tag = 1;
            }
        }
        _IDVC.modalTransitionStyle = 2;
        [UIView animateWithDuration:2 animations:^{
            [self presentViewController:_IDVC animated:YES completion:nil];
        }];
        
    }
}

#pragma mark    獲得數據
-(void)getData
{
//    NSString *cityStr = [_cityName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *cityStr = [_cityName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *ver = [_version substringToIndex:3];
    NSString *urlString = [NSString stringWithFormat:@"http://wl.myzaker.com/?_appid=iphone&_v=%@&_version=%@&c=columns&city=%@", _version, ver, cityStr];
//    NSLog(@"%@", urlString);
    [InternetDataRequest getDataByString:urlString BodyDic:nil WithDataBlock:^(id data) {
        NSDictionary *dic = [data objectForKey:@"data"];
        NSArray *array = [dic objectForKey:@"columns"];
        for (NSDictionary *dic in array)
        {
            LQYChannelDetailModal *modal = [[LQYChannelDetailModal alloc]init];
            [modal setValuesForKeysWithDictionary:dic];
            [_sectionArray addObject:modal];
        }
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
        [_loadingView removeFromSuperview];
    }];
}










- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
